package com.laysonx.easy.invoke.core;

import com.laysonx.easy.invoke.support.Param;
import com.laysonx.easy.invoke.support.Resource;
import com.laysonx.easy.invoke.support.ResourcePool;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 装配数据清理、数据验证处理器
 *
 * @author: Laysonx
 * @date: 2019/9/27 15:51
 */
public class ResourcePoolProcessor implements BeanPostProcessor, ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        // 获取ResourcePool
        ResourcePool resourcePool = context.getBean(ResourcePool.class);
        // 判断当前类 是否符合 pool.rule
        String[] matchPaths = resourcePool.getMatchPaths();
        for(String path : matchPaths){
            if(bean.getClass().toString().contains(path)){

                Resource resource = new Resource();
                Method[] methods = bean.getClass().getMethods();
                if(methods != null && methods.length != 0){
                    String classPath = bean.getClass().toString();
                    resource.setPath(classPath);
                    resource.setName(beanName);

                    List<com.laysonx.easy.invoke.support.Method> resourceMethods = new ArrayList<>();
                    for (Method method : methods) {

                        // TODO 排除object方法
                        com.laysonx.easy.invoke.support.Method resourceMethod = new com.laysonx.easy.invoke.support.Method();
                        resourceMethod.setName(method.getName());

                        List<Param> params = new ArrayList<>();
                        Param param = new Param();
                        Class<?>[] parameterTypes = method.getParameterTypes();
//                        param.setTypes(parameterTypes);
                        params.add(param);

                        resourceMethod.setParams(params);
                        resourceMethods.add(resourceMethod);
//                        resource.setMethods(resourceMethods);

                    }

                    // 符合则解析
                    resourcePool.addResource(resource);
                }
            }
        }

        return bean;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
